import { getValue,clone,mergeAttr} from "../../util/ObjectUtil.js";
import {VNode} from "../../vdom/vnode.js"
export function vforInit(vm,elm,parent,instructions) {
    let virtualNode = new VNode(elm.nodeName,elm,[],"",getVirtualNodeData(instructions)[2],parent,0);
    virtualNode.instructions = instructions;
    let childs = analysisInstructions(vm, instructions, elm, parent);//分析指令,并给虚拟父级添加相应字节点
    virtualNode.temps = childs;
    return virtualNode;
}

function analysisInstructions(vm,instructions,elm,parent) {
    let insSet = getVirtualNodeData(instructions) //得到指令数据
    let obj = mergeAttr(vm._data,parent.env)
    let  dataSet = getValue(obj,insSet[2]); //从vue-data中找到对应vue-data-value
    
    if (!dataSet) {
        throw new insSet[2]+"不存在与vue-data中";
    }
    let resultSet = [];
    for (let i = 0; i < dataSet.length; i++) {
        let tempDom = document.createElement(elm.nodeName);//创建要复制的dom元素，未挂载
        tempDom.innerHTML = elm.innerHTML;
        let env = analysisKV(insSet[0],dataSet[i],i);
        tempDom.setAttribute("env",JSON.stringify(env)); //把局部变量先添加到属性上，方便后面添加到vnode的env上
        parent.elm.insertBefore(tempDom,elm);
        resultSet.push(tempDom);
        console.log(tempDom);
    }
    parent.elm.removeChild(elm); //将vfor原始节点删去
    return resultSet; //返回复制节点的数组
}

//解析v-for的数据
function getVirtualNodeData(instructions) {
    let insSet = instructions.trim().split(" ");
    //insSet : key in value; (key,index) in value;key of value;
    if (insSet.length != 3 || insSet[1] != "in" && insSet[1] != "of") {
        throw new Error("error");
    }
    return insSet;
}

//分析每一个元素的v-for中局部变量key in list中的key和vue-data中对应的值
//返回每个元素的局部变量 env = {key: {…}, index: 0};
function analysisKV(key,value,index) {
    key = key.trim();
    if (key[0] == "(") {//带括号的形式(key,index),先去掉括号
        key = key.substring(1, key.length - 1);
    }
    let keys = key.split(",");
    if (keys.length == 0) {
        throw new Error("error");
    }
    let obj = {};
    if (keys.length >= 1) {
        
        obj[keys[0].trim()] = clone(value); 
        //只有key没有index的情况直接在对象中添加key
    }
    if (keys.length  >= 2) {
        obj[keys[1].trim()] = index;
    }
  
    return obj;
}